package com.ilancuo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class CreateThreadByImplementsCallable implements Callable<Integer> {

    @Override
    public Integer call() {
        AtomicInteger count = new AtomicInteger();
        IntStream.rangeClosed(0, 10).forEach(i -> {
            System.out.println(Thread.currentThread().getName() + " " + i);
            count.getAndIncrement();
        });
        return count.get();
    }

    public static void main(String[] args) {
        CreateThreadByImplementsCallable target = new CreateThreadByImplementsCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(target);

        IntStream.rangeClosed(0, 10).forEach(i -> {
            System.out.println(Thread.currentThread().getName() + " 的循环变量 i 的值：" + i);
            if (i == 8) {
                new Thread(futureTask, "有返回值的线程").start();
            }
        });

        try {
            System.out.println("有返回值线程的返回值：" + futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
